#include "mainwindow.h"
#include "ui_mainwindow.h"

extern QString qssStype;

QString MainWindow::version = "1.1.3";
QString listStyle;
int MainWindow::totalTomatoes = 0;
QString MainWindow::ApplicationName = QString("transaction manager v_%1").arg(MainWindow::version);

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow),m_currentTask(nullptr)
    , m_updater(new Updater(this))
    , m_note(nullptr)
{


    ui->setupUi(this);


    // 设置字符集编码

    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    this->setWindowTitle(ApplicationName);
    this->setWindowIcon(QIcon(":/pics/trayico"));
    // 禁止调整窗口大小
    setFixedSize(this->width(), this->height());

    // 菜单栏
    QMenuBar *mBar = menuBar();
    QMenu *file = mBar->addMenu("文件");
    QMenu *task = mBar->addMenu("管理");
    QMenu *tools = mBar->addMenu("工具");
    QMenu *others = mBar->addMenu("其它");

    // 菜单项，添加动作
    QAction *newTask = others->addAction("bug反馈");
    connect(newTask, &QAction::triggered,[=](){
        QMessageBox::information(this, "bug反馈", QString("可以将bug相关信息(bug出现时的操作，及bug的表现)提交至邮箱。\n邮箱：15355407358@163.com\n邮件主题为：transaction manager v_%1 bug反馈").arg(version),"确定");

    });

    newTask = others->addAction("检查更新");
    connect(newTask, &QAction::triggered, this, &MainWindow::checkUpdate);

    newTask = tools->addAction("数据统计");
    connect(newTask, &QAction::triggered, this, &MainWindow::openOverviewCharts);

    newTask = task->addAction("新建任务");
    connect(newTask, &QAction::triggered,[=](){
        CreateTask *CnewTask = new CreateTask();

        connect(CnewTask, &CreateTask::TableAddTask, this, &MainWindow::TableAddTask);

        CnewTask->show();

    });

    newTask = task->addAction("设置");
    connect(newTask, &QAction::triggered,[=](){
        Settings *settings = new Settings();
        connect(settings, &Settings::doSettings, this, &MainWindow::update_settings);
        settings->show();

    });

    newTask = file->addAction("导入任务");
    connect(newTask, &QAction::triggered, [=]{
       QString fileName = QFileDialog::getOpenFileName(this,"导入文件",".","*.csv");
       if (!Ndb::DbInputCsv(fileName, ""))
       {
           QMessageBox::warning(this, "错误", "任务导入失败！", "确定");
           return;
       }
       loadTaskItem();
       showData();
       qDebug() << "get fileName " << fileName;
    });

    newTask = file->addAction("导出任务");
    connect(newTask, &QAction::triggered, [=]{
       QString fileName = QFileDialog::getSaveFileName(this,"导出文件","./out.csv","*.csv");
       Ndb::DbOutputCsv(fileName);
       qDebug() << "get fileName " << fileName;
    });

    // 设置主窗口关闭后退出程序
    setAttribute(Qt::WA_QuitOnClose, true);





    InitWidget();

    initTrayIcon();


    InitTableMenu();

    // 第一次启动时，显示昨日统计数据
    showYesterdayPie();
}


void MainWindow::initTrayIcon()
{




    // 托盘显示

    m_trayIcon = new QSystemTrayIcon(this);
    m_trayIcon->setIcon(QIcon(":/pics/trayico"));
    m_trayIcon->setToolTip(ApplicationName); //提示文字

    m_trayIcon->show();
    m_trayIcon->showMessage("提示信息",QString("%1 已启动").arg(ApplicationName),QSystemTrayIcon::Information,5000);


    // 托盘右键菜单
    QAction *pNew;
    this->m_topMenu = new QMenu(this);

    pNew = this->m_topMenu->addAction("显示窗口");
    connect(pNew,&QAction::triggered,this,&MainWindow::showWindow);

    pNew = this->m_topMenu->addAction("退出程序");
    connect(pNew,&QAction::triggered,this,&MainWindow::trayQuit);

    m_trayIcon->setContextMenu(m_topMenu);
    connect(m_trayIcon,&QSystemTrayIcon::activated,this,&MainWindow::TrayIconAction);//连接信号与槽，实现单击图标恢复窗口的功能，槽是自定义的槽

}


void MainWindow::InitWidget()
{

    // 四象限表格初始化
    initFourQuadrantTable();

    // next to do list
    initNextToDoTable();

    // current task init
    initCurrentTaskW();
    // taskTimer init
    initTaskTimer();

    // init subTaskTable
    initSubTaskTable();



}

void MainWindow::InitTableMenu()
{
    //打开右键菜单属性

    for (int i=0; i< FOURTABLENUM; ++i)
    {
        m_tables[i]->m_table->setContextMenuPolicy(Qt::CustomContextMenu);
        connect((abstractTable *)m_tables[i], &abstractTable::menuRequested, this, &MainWindow::on_customContextMenuRequested);
    }
    m_next_to_do_table->m_table->setContextMenuPolicy(Qt::CustomContextMenu);
    connect((abstractTable *)m_next_to_do_table, &abstractTable::menuRequested, this, &MainWindow::on_customContextMenuRequested);

}

void MainWindow::initCurrentTaskW()
{
    ui->describeEdit->setReadOnly(true);

    m_note = new Notes(ui->noteEdit, ui->note_front, ui->note_next, ui->note_save,ui->note_edit_time, ui->note_page);
}

void MainWindow::initFourQuadrantTable()
{


    taskTable::fourQuadrantTables[0] = new taskTable(ui->table1);
    taskTable::fourQuadrantTables[1] = new taskTable(ui->table2);
    taskTable::fourQuadrantTables[2] = new taskTable(ui->table3);
    taskTable::fourQuadrantTables[3] = new taskTable(ui->table4);

    m_tables = taskTable::fourQuadrantTables;

    for (int i=0; i<4; ++i){
        connect(m_tables[i]->m_table, &QTableWidget::cellClicked,
                [=](int row, int column)
                {
                    qDebug() << "click row " <<row << " column " << column << endl;
                   if (column != taskTable::DELETE) return;
                   QTableWidgetItem *item = m_tables[i]->m_table->item(row, taskTable::NAME);
                   int taskId = m_tables[i]->m_table->item(row, taskTable::ID)->text().toInt();
                  int ret = QMessageBox::question(this,
                   "提示", "删除任务 "+item->text(), "确定", "取消"
                                                  );
                  switch(ret)
                  {
                    case 0:
                      qDebug() << "click 确定";

                      this->TableRemoveTask(i, row);
//                      this->TableRemoveTask_todolist_fromID(taskId);
                      break;
                    case 1:
                      qDebug() << "click 取消";
                      break;
                  }
                }
                );
    }

}

void MainWindow::initTaskTimer()
{
    QTimer *t = new QTimer(this);
    m_task_timer = new taskTimer(ui->todayTomatoRecord, ui->lcdTaskTimer, t, ui->task_state, ui->startTimerBtn, ui->pauseTimerBtn);

    connect(m_task_timer, &taskTimer::SendTaskEndSignal, this, &MainWindow::timerEnd);

    m_task_timer->TaskReset();
}

void MainWindow::initNextToDoTable()
{
    this->m_next_to_do_table = new nextToDoTable(ui->nextDoTableList);

    connect(m_next_to_do_table->m_table, &QTableWidget::cellClicked,
            [=](int row, int column)
            {

                qDebug() << "click row " <<row << " column " << column << endl;
               if (column != nextToDoTable::DELETE) return;
               QTableWidgetItem *item = m_next_to_do_table->m_table->item(row, nextToDoTable::NAME);
               int taskId = m_next_to_do_table->m_table->item(row, nextToDoTable::ID)->text().toInt();
              int ret = QMessageBox::question(this,
               "提示", "删除任务 "+item->text(), "确定","取消"
                                              );
              switch(ret)
              {
                case 0:
                  qDebug() << "click 确定";
                  this->TableRemoveTask_fromID(taskId);

                  break;
                case 1:
                  qDebug() << "click 取消";
                  break;
              }
            }
            );
    // current task init
    connect(m_next_to_do_table, &nextToDoTable::selectCurrentTask, this, &MainWindow::showCurrentTask);
}

void MainWindow::initSubTaskTable()
{
    m_sub_task_table = new subTaskTable(ui->subTaskTable);
    // 绑定事件
    connect(m_sub_task_table, &subTaskTable::selectCurrentSubTask, this, &MainWindow::showCurrentSubTask);


    // 修改子任务表格时自动修改对应的标签
    connect(m_sub_task_table->m_table, &QTableWidget::itemChanged, this, &MainWindow::connect_subTable_subLabel);
}



void MainWindow::showCurrentSubTask(const subTask &subtask)
{

    this->ui->curSubTask->setText(subtask.name);
    this->ui->curSubTask_title->setText(subtask.name);
    this->ui->subTaskTomatoInfo->setText(QString("%1/%2").arg(subtask.achieve).arg(subtask.tomato));

}

void MainWindow::doNextTask()
{
    int next_to_do_row = m_next_to_do_table->getNextTaskRow();
    if (next_to_do_row == -1) {
        QMessageBox::information(this,
         "提示", "全部任务执行完毕!","确定");
        return;
    }
    QTableWidgetItem *item = m_next_to_do_table->m_table->item(next_to_do_row, nextToDoTable::NAME);
    int ret = QMessageBox::question(this,
     "提示", "执行下一个任务  "+item->text(), "确定", "取消"
                                    );
    switch(ret)
    {
      case 0:
        qDebug() << "click 确定";
        emit m_next_to_do_table->m_table->cellDoubleClicked(next_to_do_row,nextToDoTable::STATE);
        break;
      case 1:
        qDebug() << "click 取消";
        break;
    }
}

void MainWindow::showWindow()
{
    showAllWindows();
    this->showNormal();
    this->activateWindow();
}

void MainWindow::taskLog(timeVecs *time_vecs, bool isRest)
{
    int logid = -1;
    if (isRest)
        logid = Ndb::addTaskLog(m_currentTask->m_id, "rest", 4, taskItem::config->m_tomatoTime_rest, true);
    else
        logid = Ndb::addTaskLog(m_currentTask->m_id, m_currentTask->m_taskName, m_currentTask->m_sort, taskItem::config->m_tomatoTime, true);

    for (timeVec &t: *time_vecs)
        Ndb::addTimeVec(m_currentTask->m_id, logid, t.first, t.second);

}

void MainWindow::showYesterdayPie()
{
    if (taskItem::config->m_tomatoAchieveToday == 0)
    {
        OverviewChart *chat = new OverviewChart;
        chat->selectComboxIndex(1);
        chat->show();
        chat->activateWindow();
    }
}

void MainWindow::hideAllWindows()
{
    QWindowList wlist = QApplication::allWindows();
    foreach(auto &w, wlist)
    {
        w->hide();
    }
}

void MainWindow::showAllWindows()
{
    QWindowList wlist = QApplication::allWindows();
    foreach(auto &w, wlist)
    {
        if (w->type() != Qt::WindowType(Qt::Popup))
        {
            w->show();

        }
        qDebug() << w->title() << " " << w->type();

    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::taskListAddTask(taskItem &task)
{
    if (!taskItem::all_tasks.contains(task.m_id))
    {
        taskItem::all_tasks.insert(task.m_id,&task);
        connect(&task, &taskItem::taskItemChange, this, &MainWindow::detected_taskItem_change);
    }
    else taskListUpdateTask(task);

}

void MainWindow::taskListUpdateTask(taskItem &task)
{
    taskItem *task_ = taskItem::all_tasks.value(task.m_id);
//    task_->copy(task);

    emit task_->taskItemChange(task);
    qDebug() << "emit taskItemChange ";
}



void MainWindow::loadTaskItem(){


    QString sql = QString("select * from %1").arg(Ndb::tableName);
    if (!Ndb::query.exec(sql)) {qDebug() << "Error: Fail to select." << Ndb::query.lastError();return;}
    taskItem::all_tasks.clear();
    QStringList finishedTasksId;



    while (Ndb::query.next()){
        int tomatoesTotal = Ndb::query.value("tomatoesTotal").toUInt();
        int tomatoesAchieveTotal = Ndb::query.value("tomatoesAchieveTotal").toUInt();
        int id = Ndb::query.value("id").toInt();
        int days = Ndb::query.value("days").toInt();
        if (tomatoesTotal <= tomatoesAchieveTotal && days >= 0)
        {
            finishedTasksId << QString("%1").arg(id);
            continue;
        }

        taskItem *task_item = new taskItem(
                    Ndb::query.value("id").toInt(),
                    Ndb::query.value("taskName").toString(),
                    Ndb::query.value("sort").toInt(),
                    Ndb::query.value("eachDayTomatoes").toUInt(),
                    Ndb::query.value("tomatoesTotal").toUInt(),
                    Ndb::query.value("todayAchieveTomato").toUInt(),
                    Ndb::query.value("tomatoesAchieveTotal").toUInt(),
                    Ndb::query.value("today").toDateTime(),
                    Ndb::query.value("days").toInt(),
                    Ndb::query.value("startDate").toDateTime(),
                    Ndb::query.value("describe").toString()
                    );

        taskListAddTask(*task_item);
    }

    // load sub task
    for(auto iter = taskItem::all_tasks.constBegin(); iter != taskItem::all_tasks.constEnd(); ++iter)
        (*iter)->loadSubTask();


    if (m_config->m_finishedTask == "delete")
    {
        sql = QString("delete from %1 where id in (%2)").arg(Ndb::tableName).arg(finishedTasksId.join(','));
        Ndb::query.prepare(sql);
        if (!Ndb::query.exec())
        {
            qDebug() << "delete error " << Ndb::query.lastError();
        }
    }
}

void MainWindow::TableAddTask(taskItem &task)
{
    int sort = task.m_sort;
    taskListAddTask(task);
    m_tables[sort]->addTask(task);

    m_next_to_do_table->addTask(task);
}

void MainWindow::TableUpdateTask(taskItem &task)
{
    qDebug() << "recv TableUpdateTask ";
    int sort = task.m_sort;
    taskListUpdateTask(task);
//    m_tables[sort]->updateTask(task);

//    m_next_to_do_table->updateTask(task);
}

void MainWindow::TableRemoveTask(int sort, int row)
{
    qDebug() << "sort " << sort << "row " << row ;
    int id = m_tables[sort]->m_table->item(row, taskTable::ID)->text().toInt();
    qDebug() << "id " << id;
    taskItem::all_tasks.remove(id);

    QString sql = QString("delete from %1 where id=%2").arg(Ndb::tableName).arg(id);
    Ndb::query.prepare(sql);
    if (!Ndb::query.exec()) {
        qDebug() << "delete error " << Ndb::query.lastError();
    }


    m_tables[sort]->removeTask(row);
    this->TableRemoveTask_todolist_fromID(id);
}


void MainWindow::TableRemoveTask_fromID(int id)
{
    int rows;
    int item_id;
    bool flag = false;
    int sort;
    int row;


    for (sort=0; sort<4; ++sort){
        rows = m_tables[sort]->m_table->rowCount();
        for (row=0; row<rows; ++row){
            item_id = m_tables[sort]->m_table->item(row, taskTable::ID)->text().toInt();
            if (item_id == id){
                flag = true;
                break;
            }
        }
        if (flag) break;
    }
    if (!flag) return;

    qDebug() << "sort " << sort << "row " << row ;

    qDebug() << "id " << id;
    taskItem::all_tasks.remove(id);

    QString sql = QString("delete from %1 where id=%2").arg(Ndb::tableName).arg(id);
    Ndb::query.prepare(sql);
    if (!Ndb::query.exec()) {
        qDebug() << "delete error " << Ndb::query.lastError();
    }


    m_tables[sort]->removeTask(row);
    this->TableRemoveTask_todolist_fromID(id);
}


void MainWindow::TableRemoveTask_todolist(int row)
{

    int id = m_next_to_do_table->m_table->item(row, nextToDoTable::ID)->text().toInt();
    qDebug() << "id " << id;
    taskItem::all_tasks.remove(id);

    QString sql = QString("delete from %1 where id=%2").arg(Ndb::tableName).arg(id);
    Ndb::query.prepare(sql);
    if (!Ndb::query.exec()) {
        qDebug() << "delete error " << Ndb::query.lastError();
    }


    m_next_to_do_table->removeTask(row);
}


void MainWindow::TableRemoveTask_todolist_fromID(int id)
{
    int rows = m_next_to_do_table->m_table->rowCount();
    int item_id;
    int row;
    bool flag = false;

    for (int i=0; i < rows; ++i) {
        item_id = m_next_to_do_table->m_table->item(i, nextToDoTable::ID)->text().toInt();
        if (item_id == id) {
            row = i;
            flag = true;
            break;
        }
    }

    if (!flag) return;

    qDebug() << "id next to do list " << id;
    taskItem::all_tasks.remove(id);

    QString sql = QString("delete from %1 where id=%2").arg(Ndb::tableName).arg(id);
    Ndb::query.prepare(sql);
    if (!Ndb::query.exec()) {
        qDebug() << "delete error " << Ndb::query.lastError();
    }

    m_next_to_do_table->removeTask(row);

}




void MainWindow::showData(){

    for (auto i=0; i < 4; ++i) {
        m_tables[i]->m_table->setRowCount(0);
    }
    m_next_to_do_table->m_table->setRowCount(0);
    for (auto i=taskItem::all_tasks.constBegin(); i != taskItem::all_tasks.constEnd(); ++i) {
        m_tables[(*i)->m_sort]->addTask(*(*i));
        m_next_to_do_table->addTask(*(*i));
    }




}

void MainWindow::windowUpdateTaskTomato(taskItem &task)
{
    int task_tomato_eachday = task.m_eachDayTomatoes;    // 任务每日工作量
    int task_tomato_total = task.m_tomatoesTotal;    // 任务总工作量
    int task_todayAchieveTomato = task.m_todayAchieveTomato;   // 任务今日完成的工作量
    int tomato_achieve_total = task.m_tomatoesAchieveTotal;      // 任务总共已完成的工作量




    this->ui->dayTomatoTotalInfo->setText(QString("%2/%1").arg(task_tomato_eachday).arg(task_todayAchieveTomato));
    if (task.m_days == -1)
        this->ui->tomatoTotalInfo->setText(QString("%2/%1").arg("-").arg(tomato_achieve_total));
    else
        this->ui->tomatoTotalInfo->setText(QString("%2/%1").arg(task_tomato_total).arg(tomato_achieve_total));
    this->ui->todayTomatoRecord->setText(QString("%1").arg(taskItem::config->m_tomatoAchieveToday));
}


void MainWindow::DataBaseOpenError()
{
    QMessageBox::warning(this, "warning",Ndb::db.lastError().text());
    this->close();

}

void MainWindow::on_nextDoTableList_cellDoubleClicked(int row, int column)
{
    if (m_task_timer->isActivate()) {
        QMessageBox::warning(this, "提示", "任务执行中，无法切换!");
        return;
    }
    // 重置计数器
    m_task_timer->Init();
    for (int r=0; r<m_next_to_do_table->m_table->rowCount(); ++r){
        int tomato = this->m_next_to_do_table->m_table->item(r, nextToDoTable::TOMATO)->text().toInt();
        int achieve = this->m_next_to_do_table->m_table->item(r, nextToDoTable::TODAY)->text().toInt();
        QWidget *widget = this->m_next_to_do_table->m_table->cellWidget(r, nextToDoTable::STATE);
        QLabel *label = (QLabel *) widget;
        if (r == row)
        {


            if (achieve >= tomato)
            {
                label->setPixmap(m_next_to_do_table->m_pix_achieve);
            }
            else
            {
                label->setPixmap(m_next_to_do_table->m_pix_ready);
            }
            label->setToolTip("selected");
        }
        else{

            if (achieve >= tomato)
            {
                label->setPixmap(m_next_to_do_table->m_pix_achieve);
            }
            else
            {
                label->setPixmap(m_next_to_do_table->m_pix_not_ready);
            }

            label->setToolTip("unselected");
        }

    }
    int id = this->m_next_to_do_table->m_table->item(row, nextToDoTable::ID)->text().toInt();
    showCurrentTask(*taskItem::all_tasks.value(id));


}




void MainWindow::showCurrentTask(taskItem &task){
    m_currentTask = &task;
    QString taskName = task.m_taskName;




    QString startDate = task.m_startDate.toString(Ndb::DateFormat);
    QString endDate;
    if (task.remainDay() >= 0 )
        endDate = QDate::currentDate().addDays(task.remainDay()).toString(Ndb::DateFormat);
    else
        endDate = "-";

    // 获取当前任务笔记
    m_note->update(task.m_id);


    windowUpdateTaskTomato(task);

    this->ui->doTaskName->setText(taskName);
    this->ui->doTaskName_title->setText(taskName);

    this->ui->startDate->setText(startDate);
    this->ui->endDate->setText(endDate);

    //
    this->ui->curSubTask->setText("-");
    this->ui->curSubTask_title->setText("-");
    this->ui->subTaskTomatoInfo->setText(QString("-"));
    this->ui->describeEdit->clear();
    this->ui->describeEdit->insertPlainText(task.m_describe);


    // 修改子任务表
    if (m_currentTask->m_currentSubTaskId < 0 && m_currentTask->m_subTaskMap.size() != 0) m_currentTask->m_currentSubTaskId = task.m_id;

    this->m_sub_task_table->setCurrentSubTaskTable(task);
    // 定时器设置
    m_task_timer->TaskReset();


}




void MainWindow::timerEnd(timeVecs *ptime_vecs)
{
    // 发送信号前切换过状态
    m_trayIcon->showMessage("提示信息",QString("%1 任务 完成了一个番茄时").arg(m_currentTask->m_taskName),QSystemTrayIcon::Information,5000);
    // 工作状态计时器到期
    if (m_task_timer->m_task_state == taskTimer::REST){
        m_currentTask->addTodayTime(1);
        taskLog(ptime_vecs);
        showCurrentTask(*m_currentTask);
    } else {        // 休息状态计时器到期
        taskLog(ptime_vecs, true);

        int currentSubTaskId;
        currentSubTaskId= m_currentTask->m_currentSubTaskId;
        int task_tomato_today,task_tomato_todayAchieved;
        task_tomato_today = m_currentTask->m_eachDayTomatoes;
        task_tomato_todayAchieved = m_currentTask->m_todayAchieveTomato;

        if ( currentSubTaskId >= 0 &&  task_tomato_today > task_tomato_todayAchieved){   // 有子任务 且 今日任务任务量未达标
            qDebug() << "has sub task";
            int achieve, tomato;
            achieve = m_currentTask->m_subTaskMap[currentSubTaskId].achieve;
            tomato=  m_currentTask->m_subTaskMap[currentSubTaskId].tomato;
            if ( achieve >= tomato){        // 当前子任务已完成
                qDebug() << "current subtask completed";
                int subTask_row;
                subTask_row = 0;
                bool flag;
                flag = false;
                QString name = m_currentTask->m_subTaskMap[currentSubTaskId].name;
                for (subTask_row=0; subTask_row< m_sub_task_table->m_table->rowCount(); ++subTask_row){
                    if (m_sub_task_table->m_table->item(subTask_row, subTaskTable::NAME)->text() == name){
                        flag = true;
                        break;
                    }
                }
                if (!flag) QMessageBox::critical(this,"错误","子任务表中未找到 "+name+" 项","确定");
                if (subTask_row != m_sub_task_table->m_table->rowCount()-1){   // 当前不是最后一个子任务
                    qDebug() << "not the last subtask subTask_row" <<subTask_row  <<"name "<< name << " rowCount " << m_sub_task_table->m_table->rowCount();
                    emit m_sub_task_table->m_table->cellDoubleClicked(subTask_row+1, subTaskTable::STATE);

                } else {    // 当前是最后一个子任务
                    qDebug() << "the last subtask";
                    doNextTask();
                }

            } else {        // 当前子任务未完成
                qDebug() << "current subtask not completed";

            }
        } else {    // 没有子任务 或 今日任务任务量达标
            if (task_tomato_today <= task_tomato_todayAchieved) doNextTask();


        }
    }

    delete ptime_vecs;
}

void MainWindow::on_startTimerBtn_clicked()
{
    if (m_currentTask == nullptr or !taskItem::all_tasks.contains(m_currentTask->m_id))
    {
        QMessageBox::warning(this, "警告", "当前没有选中的任务", "确定");
        return;
    }

    m_task_timer->TaskStart();


}

void MainWindow::on_pauseTimerBtn_clicked()
{
    m_task_timer->TaskPause();

}


void MainWindow::on_resetTimerBtn_clicked()
{
    m_task_timer->TaskReset();


}

void MainWindow::on_subTaskTable_cellDoubleClicked(int row, int column)
{
    if (m_task_timer->isActivate()) {
        QMessageBox::warning(this, "提示", "任务执行中，无法切换!");
        return;
    }
    // 重置计时器
    m_task_timer->Init();
    // 修改选中状态
    for (int r=0; r<m_sub_task_table->m_table->rowCount(); ++r){
        QWidget *widget = this->m_sub_task_table->m_table->cellWidget(r, nextToDoTable::STATE);
        QLabel *label = (QLabel *) widget;
        if (r == row){
            label->setPixmap(m_next_to_do_table->m_pix_ready);
            label->setStatusTip("selected");
        }
        else{
            label->setPixmap(m_next_to_do_table->m_pix_not_ready);
            label->setStatusTip("unselected");
        }

    }
    // 修改currentSubTaskId， 显示子任务
    int id = this->m_sub_task_table->m_table->item(row, subTaskTable::ID)->text().toInt();
    m_currentTask->m_currentSubTaskId = id;
    showCurrentSubTask(m_currentTask->m_subTaskMap.value(id));


}

void MainWindow::connect_subTable_subLabel(QTableWidgetItem *item)
{
    // 检查是否为选中子任务
    int row = item->row();
    int col = item->column();
    QLabel *label_item = (QLabel *)m_sub_task_table->m_table->cellWidget(row,subTaskTable::STATE);
    bool flag = label_item->statusTip() != "selected";
    qDebug() << "change item row " << row << "col " << col << "flag " << flag;
    if (flag) return ;




    if (subTaskTable::NAME == col or subTaskTable::TOMATO == col or subTaskTable::ACHIEVE == col){
        // 更新总任务显示参数
        windowUpdateTaskTomato(*m_currentTask);

        QString name = m_sub_task_table->m_table->item(row, subTaskTable::NAME)->text();
        ui->curSubTask->setText(name);
        ui->curSubTask_title->setText(name);
        int tomato = m_sub_task_table->m_table->item(row, subTaskTable::TOMATO)->text().toInt();
        int achieve = m_sub_task_table->m_table->item(row, subTaskTable::ACHIEVE)->text().toInt();

        ui->subTaskTomatoInfo->setText(QString("%1/%2").arg(achieve).arg(tomato));

    }

}

void MainWindow::addNewSubTaskFromW(int row, subTask subtask)
{
    m_sub_task_table->addSubTask(row, subtask);
    m_currentTask->addSubTask(subtask);
    m_currentTask->updatedb(Ndb::query);
}

void MainWindow::on_state_switch_clicked()
{
    m_task_timer->stateSwitch();
    m_task_timer->TaskReset();
}

void MainWindow::detected_taskItem_change(taskItem &task)
{
    m_next_to_do_table->updateTask(task);
    taskTable::updateTask(task);
    taskItem *old_task = taskItem::all_tasks.value(task.m_id);
    old_task->copy(task);
    if (task.m_id ==m_currentTask->m_id) showCurrentTask(*m_currentTask);

}

void MainWindow::update_settings()
{
    if (!m_task_timer->isActivate()) m_task_timer->TaskReset();
}

void MainWindow::TrayIconAction(QSystemTrayIcon::ActivationReason reason)
{

    if (reason==QSystemTrayIcon::Trigger)
    {
        showWindow();
    }


}

void MainWindow::trayQuit()
{
    emit ApplicationQuit();
}

void MainWindow::checkUpdate()
{
    m_updater->checkVersion(this, version);


}

void MainWindow::on_customContextMenuRequested(const QPoint &pos)
{
    QMenu *tableMenu = new QMenu;
    QAction *edit = tableMenu->addAction("编辑");
    tableMenu->addSeparator();
    QAction *del = tableMenu->addAction("删除");
    abstractTable *sender = (abstractTable *)QObject::sender();
    int row = sender->m_table->rowAt(pos.y());


    int taskId;
    if ((taskId=sender->getId(row)) < 0)
    {
        qDebug() << "MenuRequested invalid row " << row;
        return ;
    }

    connect(edit, &QAction::triggered, [this, taskId](){




        CreateTask *w = new CreateTask(taskId);
        connect(w, &CreateTask::TableUpdateTask, this, &MainWindow::TableUpdateTask);

        qDebug() << "get taskId " << taskId;
        taskItem *task = taskItem::all_tasks.value(taskId);
        connect(w, &CreateTask::TableAddTask, this, &MainWindow::TableAddTask);
        w->fillContent(*task);
        w->show();


    });
    connect(del, &QAction::triggered, [this, taskId, row, sender](){
        QString name = sender->getName(row);
        int ret = QMessageBox::question(this,
         "提示", "删除任务 "+name, "确定","取消"
                                        );
        switch(ret)
        {
          case 0:
            qDebug() << "click 确定";
            this->TableRemoveTask_fromID(taskId);

            break;
          case 1:
            qDebug() << "click 取消";
            break;
        }

    });

    tableMenu->exec(QCursor::pos());
    delete tableMenu;
}

void MainWindow::openOverviewCharts()
{
    OverviewChart *newChart = new OverviewChart;
    newChart->show();
}

void MainWindow::hideEvent(QHideEvent *event)
{

    if(m_trayIcon->isVisible())
    {
//        hide(); //隐藏窗口
        QWindowList wlist = QApplication::allWindows();
        foreach(auto &w, wlist)
        {
            w->hide();
        }
        event->ignore(); //忽略事件
    }

}

void MainWindow::closeEvent(QCloseEvent *event)
{

    if (taskItem::config->m_closeAndMinimize)
    {
        if(m_trayIcon->isVisible())
        {
            hide(); //隐藏窗口
            event->ignore(); //忽略事件
        }
    } else
        emit ApplicationQuit();


}
